package com.usdt.web.controller.cp.activity;

import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.usdt.common.core.domain.R;
import com.usdt.system.domain.req.ActivityTempReqVO;
import com.usdt.system.domain.req.ActivityTemplistExportReqVO;
import com.usdt.system.domain.req.ActivityUpdateStatusReqVO;
import com.usdt.system.domain.resp.ActivityTempRespVO;
import com.usdt.system.dto.cp.ActivityListExcelDTO;
import com.usdt.system.dto.cp.ActivityTempListExcelDTO;
import com.usdt.system.service.cp.ActivityTempService;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

@RestController
@Slf4j
@RequestMapping("/activityTemp")
@Tag(name = "活动模板接口")
public class ActivityTempController {
	
	@Autowired
	private ActivityTempService activityTempService;

    @PostMapping("/insert")
    @Operation(summary ="新增")
    public R<Integer> insert(@RequestBody ActivityTempReqVO vo) {
    	
    	return R.ok(activityTempService.insert(vo));
    }
    
    @GetMapping("/detail/{id}")
    @Operation(summary ="详情")
    public R<ActivityTempRespVO> insert(@Schema(description = "活动模板id")@PathVariable(value = "id", required = true) Integer id) {
    	
    	return R.ok(activityTempService.detail(id));
    }
    
    @GetMapping("/list")
    @Operation(summary ="列表")
    public R<IPage<ActivityTempRespVO>> list(
    		@Schema(description = "活动维度")@RequestParam(value = "activityCategory", required = false) Integer activityCategory,
    		@Schema(description = "活动类别")@RequestParam(value = "activityType", required = false) Integer activityType,
    		@Schema(description = "关键词")@RequestParam(value = "keyWord", required = false) String keyWord,
    		@Schema(description = "名称")@RequestParam(value = "name", required = false) String name,
    		@Schema(description = "状态 1：使用中  2：废弃")@RequestParam(value = "status", required = false) Byte status,
    		@Schema(description = "所属项目")@RequestParam(value = "deptId", required = false) String deptId,
    		@Schema(description = "活动时长min")@RequestParam(value = "activityDurationMin", required = false) BigDecimal activityDurationMin,
    		@Schema(description = "活动时长max")@RequestParam(value = "activityDurationMax", required = false) BigDecimal activityDurationMax,
    		@Schema(description = "页码")@RequestParam(value = "pageNum", required = false) Integer pageNum,
    		@Schema(description = "每页显示记录数")@RequestParam(value = "pageSize", required = false) Integer pageSize
    		) {
    	
    	return R.ok(activityTempService.list(activityCategory,activityType,keyWord,name,status,deptId,activityDurationMin,activityDurationMax,pageNum,pageSize));
    }
    
    @GetMapping("/alllist")
    @Operation(summary ="列表-全部")
    public R<List<ActivityTempRespVO>> allList(
    		@Schema(description = "名称")@RequestParam(value = "name", required = false) String name
    		) {
    	
    	return R.ok(activityTempService.allList(name));
    }
    
    @PostMapping("/update")
    @Operation(summary ="修改")
    public R<Integer> update(@RequestBody ActivityTempReqVO vo) {
    	
    	return R.ok(activityTempService.update(vo));
    }
    
    @PostMapping("/updateStatus")
	@Operation(summary = "更新状态")
	public R<Integer> updateStatus(@RequestBody ActivityUpdateStatusReqVO vo) {
    	
    	return R.ok(activityTempService.updateStatus(vo));
    }
    
    @PostMapping("/list/export")
    @Operation(summary ="列表-导出")
    public void listExport(
    		HttpServletResponse response,
    		@RequestBody ActivityTemplistExportReqVO vo) throws IOException {
    	
    	List<ActivityTempListExcelDTO> list = activityTempService.listExport(vo);
    	exportActivityExcel(response,list,ActivityTempListExcelDTO.class,"活动模板","模板信息");
    }
    
    /**
     * 导出活动信息Excel（浏览器下载）
     * @param response HttpServletResponse（用于向浏览器输出Excel）
     * @param dataList 活动数据列表（需导出的实体类集合）
     * @throws IOException IO异常（如输出流关闭失败）
     */
    public void exportActivityExcel(HttpServletResponse response, List dataList, Class clazz
    		,String excelName,String sheetName) throws IOException {
        // 1. 设置响应头（关键：避免中文乱码、指定文件类型）
    	response.addHeader("Pargam", "no-cache");
    	response.addHeader("Cache-Control", "no-cache");
    	response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        //response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); // Excel 2007+格式
    	//response.setContentType("application/octet-stream;charset=UTF-8"); // Excel 2007+格式
        response.setCharacterEncoding("utf-8");
        // 文件名编码：使用URLEncoder避免中文乱码，替换“+”为“%20”（浏览器兼容）
        String fileName = URLEncoder.encode(excelName, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + fileName + ".xlsx");

        // 2. 使用EasyExcel写入数据（try-with-resources自动关闭ExcelWriter）
        try (var excelWriter = EasyExcel.write(response.getOutputStream(), clazz).build()) {
            // 3. 构建Sheet（指定工作表名称，如“活动信息”）
            var sheet = EasyExcel.writerSheet(sheetName).build();
            // 4. 写入数据（将实体类列表映射为Excel行）
            excelWriter.write(dataList, sheet);
        }
    }
}
